<?php

namespace app\common\model\merchant;


use app\common\loader\ModelMerchant;
use app\common\model\BaseModel;
use app\common\traits\SystemMenuTrait;

/**
 * 商户系统菜单
 * Class DemoMerchantSystemMenu
 * @package app\demo\model
 */
class MerchantSystemMenuModel extends BaseModel
{
    use SystemMenuTrait;

    //
    protected $name = 'merchant_system_menu';


    protected $json = ['front'];
    // 设置字段信息
    protected $schema = [
        'id' => 'int',        // 菜单ID
        'title' => 'string',        // 菜单标题
        'pid' => 'int',        // 父ID
        'tree_path' => 'string',        // 层级路径
        'depth' => 'int',        // 层级
        'child' => 'int',        // 子菜单数
        'order_id' => 'int',        // 排序
        'api_page' => 'string',        // 菜单关联功能ID
        'icon' => 'string',        // 菜单图标
        'router_name' => 'string',        // 跌幅名称
        'router_label' => 'string',        // 路由标签
        'page_action' => 'string',        // 路由地址
        'router_file' => 'string',        // 路由文件路径
        'is_show' => 'int',        // 显视状态(0:隐藏,1:显视)
        'front' => 'json',        // 菜单信息{path:xx,name:xx,label:xx,icon:xx,filepath:xxx,title:xxx,action:xxx}
    ];

    /**
     * 删除菜单节点
     * @param $id
     * @throws \think\Exception
     */
    public function del($id): void
    {
        $this->startTrans();
        try {
            if ($this->removeOption()->where("pid", $id)->count() > 0) {
                api_exception(API_ERROR, "该权限还有下级权限,请先维护下级权限");
            }
            $pid = $this->removeOption()->where('id', $id)->value(null, "pid");
            if ($pid > 0) {
                $this->db()->removeOption()->where('id', $id)->dec("child")->update();
            }
            ModelMerchant::MerchantRolesActions()->where(["menu_id" => $id])->delete();
            $this->removeOption()->where(["id" => $id])->delete();
            $this->commit();
        } catch (Exception $e) {
            $this->rollback();
            throw $e;
        }

    }

}
